<?php
class CallbackController extends BaseController
{
    public $data;
    public $where;
    public $result;
    public $channel;
    public $webConfig;
    public $db;
    public $openId;
    public function init()
    {
        $this->db  = $this->mysql();
        $config    = $this->db->select('config', '*');
        $webConfig = [];
        foreach ($config as $key => $value) {
            $webConfig[$value['name']] = $value['value'];
        }
        $this->webConfig = $webConfig;
    }
    /**
     * aliba回调地址
     * {$url}/callback/aliba
     **/
    public function alibaAction()
    {

        $this->channel               = 'aliba';
        if(empty($_POST)){
        	$this->where                 = $_GET;
        }else{
        	$this->where                 = $_POST;
        }

        $this->where['order_number'] = $this->where['orderid'];
        $this->where['account']      = $this->where['mobile'];
        file_put_contents('callback.txt', var_export($this->where, true) . PHP_EOL, FILE_APPEND);
        switch ($this->where['state']) {
            case 2:
                $this->data = [
                    'callback_time'   => time(),
                    'callback_result' => '充值中',
                ];
                $res = 'no';
                break;
            case 3:
                $this->data = [
                    'callback_time'   => time(),
                    'status'          => 'success',
                    'callback_result' => '成功',
                ];
                $res = 'OK';
                break;
            case 4:
                $this->data = [
                    'callback_time'   => time(),
                    'status'          => 'issue_orders',
                    'callback_result' => '待补单',
                ];
                $res = 'no';
                break;
        }
        $this->update();
        if ($this->result) {

            return $res;
        }
        return $res;
    }

    // 微信退款回调
    public function RefundAction()
    {
        file_put_contents('refund.txt', '进入回调：' . date('Y-m-d H:i：s') . PHP_EOL, FILE_APPEND);
    }
    /**
     * jishuapi回调地址
     * {$url}/callback/jisu
     **/
    public function JisuAction()
    {
        $this->channel = 'jisu';
        $this->where   = $_POST;
        file_put_contents('callback.txt', var_export($this->where, true) . PHP_EOL, FILE_APPEND);
        $this->where['order_number'] = $_POST['outorderno'];
        $data                        = [
            'orderno'        => $this->where['orderno'],
            'outorderno'     => $this->where['outorderno'],
            'mobile'         => $this->where['mobile'],
            'rechargestatus' => $this->where['rechargestatus'],
            'amount'         => $this->where['amount'],
            'totalfee'       => $this->where['totalfee'],
        ];
        $appsecret = '9Fb7ucxbtNttsX34tkYciink0ep0uJCW'; //用户appsecret
        file_put_contents('callback.txt', var_export($data, true) . PHP_EOL, FILE_APPEND);

        if (checkSign($data, $appsecret, $this->where['sign'])) {

            //1成功 2处理失败 0处理中
            switch ($this->where['rechargestatus']) {
                case '1':
                    {
                        $this->data = [
                            'callback_time'   => time(),
                            'status'          => 'success',
                            'callback_result' => '成功',
                        ];
                        break;
                    }
                case '2':
                    {
                        $this->data = [
                            'callback_time'   => time(),
                            'status'          => 'issue_orders',
                            'callback_result' => '待补单',
                        ];
                        break;
                    }
            }
            $this->update();
            if ($this->result) {
                echo 'success';
            }

            exit();
        }
    }

    public function update()
    {
	try{
        $this->result = $this->db->action(function ($database) {
            $orderInfo = $database->get('cecharge_order', '*', [
                'order_number' => $this->where['order_number'],
                'deletetime'   => null,
                'pay_list'     => '已支付',
                'status'       => 'wait',
            ]);
            file_put_contents('callback.txt', var_export($this->data, true) . PHP_EOL, FILE_APPEND);
            $result = $database->update('cecharge_order', $this->data, [
                'order_number' => $this->where['order_number'],
                'deletetime'   => null,
                'pay_list'     => '已支付',
                'status'       => 'wait',
            ]);
            if ($result->rowCount() <= 0) {
            	echo '1';
                dump_log('回调地址： ' . $_SERVER['REQUEST_URI'] . http_build_query($this->where) . ' 状态： 订单更新失败', $this->channel . '_callback_error.txt');
                return false;
            }
            if (isset($this->where['state']) && $this->where['state'] == 3 || isset($this->where['rechargestatus']) && $this->where['rechargestatus'] == 1) {
                $result = $database->delete('cecharge_notify', [
                    'order_number' => $this->where['order_number'],
                ]);
                if ($result->rowCount() <= 0) {
                    dump_log('回调地址： ' . $_SERVER['REQUEST_URI'] . http_build_query($this->where) . ' 状态： 订单记录删除失败', $this->channel . '_callback_error.txt');
                    echo '2';
                    return false;
                }
            }
            dump_log('回调地址： ' . $_SERVER['REQUEST_URI'] . http_build_query($this->where) . ' 状态： 成功', $this->channel . '_callback_success.txt');
            // 如果成功则发送消息
            $database->insert('notify', [
                'mobile'      => $this->where['mobile'],
                'amount'      => $orderInfo['recharge_amount'],
                'user_number' => $orderInfo['user_number'],
                'type'        => '话费',
                'createtime'  => time(),
            ]);
            // 获取用户openid
            $wechat_number = $database->get('user', 'wechat_user_number', [
                'user_number' => $orderInfo['user_number'],
            ]);
            $openid = $database->get('wechat_user', 'openid', [
                'wechat_user_number' => $wechat_number,
            ]);

            $subscribeMessageObj = new Wechat\SubscribeMessage();
            $messageData         = [
                'amount3'           => [
                    'value' => $orderInfo['recharge_amount'],
                ],
                'phone_number6'     => [
                    'value' => $this->where['mobile'],
                ],
                'character_string7' => [
                    'value' => $orderInfo['order_number'],
                ],
                'date2'             => [
                    'value' => date('Y-m-d H:i:s'),
                ],
                'thing8'            => [
                    'value' => '您充值的' . $orderInfo['recharge_amount'] . '元话费已到账,请查收',
                ],

            ];
            $result = $subscribeMessageObj->sendSubMessage([
                'appid'      => $this->webConfig['appid'],
                'app_secret' => $this->webConfig['secret'],
            ], $openid, $this->webConfig['template_id'], $messageData);
            return true;
        });
	} catch (Exception $e) {
    file_put_contents('break_error.txt',var_export($e->getMessage(),true) . PHP_EOL, FILE_APPEND);
    // die(); // 终止异常
}
    }

    // 聚合平台余额回调地址
    public function notifyAction()
    {
        try {
            $account_balance = $this->getRequest()->getPost('account_balance', 0);
            $channel_number  = $this->getRequest()->getPost('channel_number', '');
            $result          = $this->db->update('aggregation_channel', [
                'account_balance' => $account_balance,
            ], [
                'channel_number' => $channel_number,
            ]);
            die(json_encode(['success' => 'true']));
        } catch (Exception $e) {
            file_put_contents('notify.txt', var_export($e->getMessage(), true) . PHP_EOL, FILE_APPEND);
        }

    }

    public function notifyuserAction()
    {

        try {
            
            $param = $_POST;
            if (empty($param)) {
                //   echo '没有获取到订单...<br>';
                exit;
            }
         
            // 0 成功 5失败 7可疑
            file_put_contents(date('Y-m-d').'order_notify.txt', var_export($param, true) . PHP_EOL, FILE_APPEND);
            if ($param['order_status'] == 5) {
            	/* $order = $this->db->get('aggregation_order', '*', ['cloud_order_number' => $param['order_number']]);
                //   echo '获取到失败订单' . $param['order_number'] . '...<br>';
                dump_log('外挂回调：充值失败新-' . $param['order_number'], 'notifyuser_error');
                	dump_log('外挂回调：充值失败003-' . $param['cloud_order_number'].var_export($param,true), 'notifyuser_error');
			        $param = [
                        'cecharge_channel_log' => $order['cecharge_channel_log'],
                        'order_number'         => $order['order_number'],
                        'authorize_number'     => $order['authorize_number'],
                        'payment_amount'       => $order['payment_amount'],
                        'status'			   => '未知错误',
                        'updatetime'		   => time(),
                        'remarks'              => $param['remarks'],
                    ];
                    $result = $this->db->update('aggregation_order',$param,[
                   		 'cloud_order_number' => $order['cloud_order_number'],
                   	]);
                   	if($result->rowCount()<1){
                   		dump_log('外挂回调：充值失败001-' . $param['cloud_order_number'].var_export($param,true), 'notifyuser_error');
                   	dump_log('外挂回调：充值失败002-' . $param['cloud_order_number'].var_export($this->db->error(),true), 'notifyuser_error');
                   		 die(json_encode(['success' => false]));
                   	}
                   	
                     die(json_encode(['success' => true]));
                // echo '<pre>';
                **/
                 $result = $this->resubmit($param);
                if ($result == true) {
                 	 dump_log('外挂回调：充值失败-成功-' . $param['order_number'], 'notifyuser_error');
                     die(json_encode(['success' => true]));
                }
                dump_log('外挂回调：充值失败-失败-' . $param['order_number'], 'notifyuser_error');
                die(json_encode(['success' => false]));
            }
            if ($param['order_status'] == 0) {
                //  echo '获取到成功订单'.$param['order_number'].'...<br>';
                // 查询订单
    //             $order1 = $this->db->get('aggregation_order', '*', ['order_number' => $param['order_number']]);
                
                
				// if(is_null($order1)){
					$order = $this->db->get('aggregation_order', '*', ['cloud_order_number' => $param['order_number']]);
				// }else{
				// 	$order= $order1;
				// }
                if ($order['status'] == '充值完成' && $order['notify_result'] =='success') {
                    die(json_encode(['success' => true]));
                }
                if (is_null($order)) {
                    dump_log('外挂回调：订单不存在', 'notifyuser_error');
                    // 订单不存在停止回调
                    die(json_encode(['success' => false]));
                }
                $params = [
                    'outorderno'     => $order['cloud_order_number'],
                    'order_number'   => $order['order_number'],
                    'mobile'         => $order['mobile'],
                    'status'         => 1,
                    'amount'         => $order['amount'],
                    'sp'			 => $param['sp'],
                    'payment_amount' => $order['payment_amount'],

                ];
                $appsecret = $this->db->get('aggregation_authorize', 'appsecret', [
                    'authorize_number' => $order['authorize_number'],
                ]);
                if (is_null($appsecret)) {
                    dump_log('外挂回调：授权信息错误-' . $param['order_number'], 'notifyuser_error');
                    // 授权信息错误停止回调
                    die(json_encode(['success' => false]));
                }

                // 根据订单状态进行回调
                if ($order['status'] == '充值中') {
                    $this->db->update('aggregation_order', [
                        'notify_result'    => '等待回调',
                        'cecharge_channel' => $param['channel_number'],
                        'remarks'          => $param['commit_type'].' '.$param['remarks'],
                        'sp'               => $param['sp'],
                        'status'           => '充值完成',
                    ], [
                        'cloud_order_number' => $order['cloud_order_number'],
                    ]);
                    $channel_account_balance =    $this->db->get('aggregation_channel', 'account_balance', [
		                'channel_number' => $param['channel_number'],
		            ]);
                    $this->db->insert('aggregation_channel_turnover', [
                                'channel_number' => $param['channel_number'],
                                'money'          => $order['amount'],
                                'remarks'        => $order['cloud_order_number'],
                                'before'         => $channel_account_balance,
                                'after'          => $channel_account_balance - $order['amount'],
                                'status'         => '支出',
                                'createtime'     => $order['createtime'],
                            ]);
                    file_put_contents('log.txt',var_export($this->db->error(),true));
                }
                $params['sign'] = makeSign($params, $appsecret);
                //  print_r($param);
                dump_log("回调日志：".json_encode($params),'notify_text');
                $result = send_post($order['notify_url'], $params);
                dump_log('回调订单：' .$order['cloud_order_number'].','.$order['notify_url'].',结果:'.$result , 'recharge_success');
                 //echo '<pre>';
                 //print_r('用户回调结果:',$result);
                 //var_dump($order['notify_url']);
                 //print_r($params);
                 file_put_contents(date('Y-m-d').'hd.txt',date('Y-m-d H:i:s').$result . PHP_EOL, FILE_APPEND);
                if (strtolower($result) == 'success') {
                    // 回调成功
                    $result = $this->db->update('aggregation_order', [
                        'notify_result' => $result,
                        'remarks'          => $param['commit_type'].' '.$param['remarks'],
                        'status'           => '充值完成',
                        'updatetime'       => time()
                    ], [
                        'cloud_order_number' => $order['cloud_order_number'],
                    ]);
                    if ($result->rowCount() > 0) {
                        dump_log('外挂回调：成功-' . $order['cloud_order_number'], 'notifyuser_success');
                        die(json_encode(['success' => true]));
                    }
                    die(json_encode(['success' => true]));
                }
            }

            if ($param['order_status'] == 7) {
            	 $order1 = $this->db->get('aggregation_order', '*', ['order_number' => $param['order_number']]);
                
                
				if(is_null($order1)){
					$order = $this->db->get('aggregation_order', '*', ['cloud_order_number' => $param['order_number']]);
				}else{
					$order= $order1;
				}
                // $order = $this->db->get('aggregation_order', '*', ['cloud_order_number' => $param['order_number']]);
                //可疑订单
                dump_log('外挂回调：可疑订单-' . $order['authorize_number'], 'notifyuser_error');
                $this->db->update('aggregation_order', [
                    'remarks'          => $param['commit_type'].' '.$param['remarks'],
                    'cecharge_channel' => $param['channel_number'],
                    'status'           => '未知错误',
                ], [
                    'cloud_order_number' => $order['cloud_order_number'],
                ]);
                die(json_encode(['success' => true]));
            }

            // $channel_number  = $this->getRequest()->getPost('channel_number', '');
            // $result          = $this->db->update('aggregation_channel', [
            //     'account_balance' => $account_balance,
            // ], [
            //     'channel_number' => $channel_number,
            // ]);
            // if ($result->rowCount() > 1) {
            //     die(json_encode(['success' => 'true']));
            // }
        } catch (Exception $e) {
            // echo '111';
            file_put_contents('order_notify.txt', "失败" . PHP_EOL, FILE_APPEND);
            file_put_contents('order_notify.txt', var_export($e->getMessage(), true) . PHP_EOL, FILE_APPEND);
        }

    }

    public function testAction()
    {
        file_put_contents('1.txt', var_export($_POST, true));
        echo 'success';
    }
    public function resubmit($param)
    {
		 //$order1 = $this->db->get('aggregation_order', '*', ['order_number' => $param['order_number']]);
                
                
			// 	if(is_null($order1)){
		$this->order = $this->db->get('aggregation_order', '*', ['cloud_order_number' => $param['order_number']]);
				// }else{
				// 	$this->order= $order1;
				// }
        // if ($this->order['status'] == '未知错误') {
        //     dump_log('状态异常结束：' . $this->order['order_number'] . $this->order['status'], 'recharge_order_commit_error');
        //     return true;
        // }
        $this->order['cecharge_channel'] = $param['channel_number'];
        $this->order['remarks']          = $param['remarks'];
        dump_log('外挂回调：充值失败-' . $param['order_number'], 'notifyuser_error');
        // echo '<pre>';
        // print_r($this->order);
        $template      = json_decode($this->order['template_info'], true);
        $this->channel = $this->db->select('aggregation_channel', '*', [
            'url[!]'         => '',
            'notify_url[!]'  => '',
            'channel_number' => explode(',', $template['aggregation_channel_ids']),
        ]);

        if (empty($this->channel)) {

            dump_log('未获取到通道：' . $template['aggregation_channel_ids'], 'recharge_shop_error');
            return false;
        }
        $phonearea       = file_get_contents('https://cx.shouji.360.cn/phonearea.php?number=' . $this->order['mobile']);
        $this->phonearea = json_decode($phonearea, true);
        $result          = $this->db->action(function ($database) {
            try {
                $phonearea = $this->phonearea;
                $order     = $this->order;

                $notify_url = $database->get('config', 'value', [
                    'group' => 'notify',
                    'name'  => 'order_notify_user',
                ]);
                $res = false;
                dump_log('通道：' . json_encode($this->channel), 'recharge_success');
                $count = 0;

                foreach ($this->channel as $key => $value) {
                    // echo $value['channel_number'] . '<br>';
                    // 生成通道信息
                    $param = [
                        'cecharge_channel_log' => $order['cecharge_channel_log'],
                        'channel_number'       => $value['channel_number'],
                        'order_number'         => $order['order_number'],
                        'authorize_number'     => $order['authorize_number'],
                        'payment_amount'       => $order['payment_amount'],
                        'remarks'              => $order['remarks'],
                        'cloud_order_number'   => $order['cloud_order_number']
                    ];
                    // 如果当前通道编号，已经存在于使用记录，则跳过当次循环
                    if ($value['channel_number'] == $order['cecharge_channel'] || strpos($order['cecharge_channel_log'], $value['channel_number']) !== false) {
                        $count = $count + 1;
                        // echo '进入第' . $key . '个通道判断' . $count;
                        // 如果当前通道数量等于，最大数量，则进行退款
                        if ($count == count($this->channel)) {
                            $this->updateOrder($database, $param);
                            $res = true;
                            break;
                        }
                        continue;
                    }
                    $postParam = [
                        'channel_number'             => $value['channel_number'],
                        'order_number'               => $order['cloud_order_number'],
                        'mobile'                     => $order['mobile'],
                        'amount'                     => $order['amount'],
                        'notify_url'                 => $notify_url,
                        'secret_key'                 => $value['secret_key'],
                        'province'                   => $phonearea['data']['province'],
                        'city'                       => $phonearea['data']['city'],
                        'sp'                         => $phonearea['data']['sp'],
                        'account_balance_notify_url' => $value['notify_url'],
                    ];
                    // print_r($postParam);
                    // var_dump($value['url']);

                    $resultJson = $this->curlPost($value['url'], json_encode($postParam));
                    // echo '订单提交结果：' . $result;
                    // dump_log('订单提交结果：' . $result, 'recharge_success');
                    $result = json_decode($resultJson, true);
                    if ($result['success'] == 'true') {
                        $database->update('aggregation_order', [
                            'cecharge_channel_log' => $order['cecharge_channel_log'] . ',' . $value['channel_number'],
                        ], [
                            'cloud_order_number' => $order['cloud_order_number'],
                        ]);
                        $res = true;
                        break;
                    }
                    dump_log('订单提交失败：' . var_export($resultJson, true), 'commit_order_error');
                    $res = true;
                }
                return $res;
            } catch (Exception $e) {
                dump_log('订单提交失败3：' . var_export($e->getMessage(), true), 'recharge_success');
                return false;
            }
        });
        return $result;
    }

    public function updateOrder($database, $data)
    {
        $res = $database->update('aggregation_order', [
            'status'               => '未知错误',
            'remarks'              => $data['remarks'],
            'updatetime'           => time(),
            'cecharge_channel_log' => $data['cecharge_channel_log'] . ',' . $data['channel_number'],
        ], [
            'cloud_order_number' => $data['cloud_order_number'],
        ]);
        // file_put_contents('tuikuan.txt', var_export($res->rowCount(), true));
        // $authorize = $database->get('aggregation_authorize', '*', [
        //     'authorize_number' => $data['authorize_number'],
        // ]);
        // // 加入资金变动明细
        // $database->insert('aggregation_money_log', [
        //     'order_number'     => $data['order_number'],
        //     'authorize_number' => $authorize['authorize_number'],
        //     'before'           => $authorize['account_balance'],
        //     'money'            => $data['payment_amount'],
        //     'after'            => $authorize['account_balance'] - $data['payment_amount'],
        //     'state'            => '充值话费',
        //     'type'             => '退款',
        //     'other'            => $authorize['authorize_number'],
        //     'createtime'       => time(),
        // ]);
        // if ($database->id() < 1) {
        //     dump_log('加入资金变动明细失败' . var_export($database->error()), 'recharge_error');
        //     return false;
        // }
        // $authorize = $database->update('aggregation_authorize', [
        //     'account_balance[+]' => $data['payment_amount'],
        // ], [
        //     'appkey'     => $authorize['appkey'],
        //     'status'     => '正常',
        //     'deletetime' => null,
        // ]);
        // if ($authorize->rowCount() < 1) {
        //     dump_log('更新余额失败' . var_export($database->error()), 'recharge_update_account_balance_error');
        //     return false;
        // }
        // echo '更新订单...';
    }
    public function curlPost($url, $data)
    {
        $ch                             = curl_init();
        $params[CURLOPT_URL]            = $url; //请求url地址
        $params[CURLOPT_HEADER]         = false; //是否返回响应头信息
        $params[CURLOPT_SSL_VERIFYPEER] = false;
        $params[CURLOPT_SSL_VERIFYHOST] = false;
        $params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
        $params[CURLOPT_POST]           = true;
		$params[CURLOPT_TIMEOUT]        = 5;
        $params[CURLOPT_HTTPHEADER] = array(
            "Content-Type: application/x-www-form-urlencoded",
            "cache-control: no-cache",
        );
        $params[CURLOPT_POSTFIELDS] = $data;
        curl_setopt_array($ch, $params); //传入curl参数
        $content = curl_exec($ch); //执行
        curl_close($ch); //关闭连接

        return $content;
    }
}
